﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 异步更新窗体
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            // 启动异步任务  
            await Task.Run(() => LongRunningOperation());
        }

        private void LongRunningOperation()
        {
            for (int i = 0; i <= 100; i++)
            {
                // 更新进度条需要在UI线程上执行  
                if (progressBar1.InvokeRequired)
                {
                    progressBar1.Invoke(new Action(() => UpdateProgressBar(i)));
                }
                else
                {
                    UpdateProgressBar(i);
                }
                // 模拟耗时操作  
                System.Threading.Thread.Sleep(50);
            }
        }

        private void UpdateProgressBar(int value)
        {
            // 更新进度条的当前值  
            progressBar1.Value = value;
        }
    }
}
